package com.ruicar.afs.cloud.afscase.loanapprove.task.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.ApproveMakeLabel;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.LoanLabelInfo;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.ApproveMakeLabelService;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.LoanLabelInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCustInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCustInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.task.condition.LoanApproveTaskCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.task.condition.LoanWaitSubmitTaskCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.task.service.LoanWaitTaskService;
import com.ruicar.afs.cloud.afscase.loanapprove.task.vo.LoanWaitTaskSubmitVO;
import com.ruicar.afs.cloud.afscase.loanapprove.task.vo.LoanWaitTaskVO;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Description:放款待分配任务相关</p>
 *
 * @author xueyu.ma
 * @Version 1.0
 * @CreateDate 2020-6-12
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("放款待分配任务")
@RequestMapping("/loanTaskPool")
public class LoanWaitTaskController {

    private final LoanWaitTaskService loanWaitTaskService;
    private final CaseChannelInfoService caseChannelInfoService;
    private final CaseCustInfoService caseCustInfoService;
    private ChannelBaseInfoService channelBaseInfoService;
    private LoanLabelInfoService loanLabelInfoService;
    private CaseBaseInfoService caseBaseInfoService;
    private ApproveMakeLabelService approveMakeLabelService;
    private ApproveLoanInfoService approveLoanInfoService;
    private CaseApproveRecordService caseApproveRecordService;

    @PostMapping("/getLoanWaitTaskList")
    @ApiOperation(value = "多条件获取放款待分配任务列表")
    public IResponse<List<LoanWaitTaskVO>> queryLoanWaitTaskList(@RequestBody LoanApproveTaskCondition loanApproveTaskCondition) {
        if(loanApproveTaskCondition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            loanApproveTaskCondition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            loanApproveTaskCondition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        //流程类型：放款常规审批流程
        List<String> loanWorkflowTypeList = new ArrayList<>();
        List<String> loanApplyStatusList = new ArrayList<>();
        loanWorkflowTypeList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.LOAN_REPAIR.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.FLAW_UPDATE.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.INSPECTION.getCode());
        loanApplyStatusList.add(ApplyStatusEnum.LOAN_QUEUE.getState());
        loanApplyStatusList.add(ApplyStatusEnum.WAIT_ASSIGN.getState());
        loanApplyStatusList.add(ApplyStatusEnum.ASSIGNING.getState());
        loanApproveTaskCondition.setProcessTypeList(loanWorkflowTypeList);
        loanApproveTaskCondition.setApplyStatusList(loanApplyStatusList);
//        loanApproveTaskCondition.setApplyStatus((ApplyStatusEnum.LOAN_QUEUE.getState()));
        Page page = new Page(loanApproveTaskCondition.getPageNumber(), loanApproveTaskCondition.getPageSize());
        IPage<LoanWaitTaskVO> LoanWaitTaskVOList = loanWaitTaskService.getLoanWaitTaskVOList(page, loanApproveTaskCondition);
        LoanWaitTaskVOList.getRecords().forEach(loanWaitTaskVO -> {
            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                    .eq(CaseChannelInfo::getApplyNo, loanWaitTaskVO.getApplyNo()));
            /**渠道基本信息*/
            ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                    .eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
            loanWaitTaskVO.setCaseChannelInfo(caseChannelInfo);
            loanWaitTaskVO.setDealerName(caseChannelInfo != null ? caseChannelInfo.getDealerName() : null);
            loanWaitTaskVO.setChannelType(channelBaseInfo != null ? channelBaseInfo.getChannelType() : null);
            CaseCustInfo caseCustInfo = caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                    .eq(CaseCustInfo::getApplyNo, loanWaitTaskVO.getApplyNo())
                    .eq(CaseCustInfo::getCustRole, CustRoleEnum.MIANCUST.getCode()));
            loanWaitTaskVO.setCaseCustInfo(caseCustInfo);

            /**标签信息表**/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, loanWaitTaskVO.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, loanWaitTaskVO.getContractNo()));
            loanWaitTaskVO.setLabelList(labelList);
        });
//        if (StringUtils.isNotBlank(loanApproveTaskCondition.getCertNo())) {
//            List<LoanWaitTaskVO> LoanWaitTaskVOResult = LoanWaitTaskVOList.getRecords().stream()
//                    .filter(LoanWaitTaskVO -> LoanWaitTaskVO.getCaseCustInfo() != null
//                            && loanApproveTaskCondition.getCertNo().equals(LoanWaitTaskVO.getCaseCustInfo().getCertNo()))
//                    .collect(Collectors.toList());
//            LoanWaitTaskVOList.getRecords().clear();
//            LoanWaitTaskVOList.setRecords(LoanWaitTaskVOResult);
//        }
        if (StringUtils.isNotBlank(loanApproveTaskCondition.getDealerName())) {
            List<LoanWaitTaskVO> LoanWaitTaskVOResult = LoanWaitTaskVOList.getRecords().stream()
                    .filter(LoanWaitTaskVO -> StringUtils.isNotBlank(LoanWaitTaskVO.getDealerName())
                            && LoanWaitTaskVO.getDealerName().indexOf(loanApproveTaskCondition.getDealerName()) >= 0)
                    .collect(Collectors.toList());
            LoanWaitTaskVOList.getRecords().clear();
            LoanWaitTaskVOList.setRecords(LoanWaitTaskVOResult);
        }
        return IResponse.success(LoanWaitTaskVOList);
    }

    @PostMapping("/getWaitSubmitTaskList")
    @ApiOperation(value = "多条件获取放款待提交任务列表")
    public IResponse<List<LoanWaitTaskSubmitVO>> getWaitSubmitTaskList(@RequestBody LoanWaitSubmitTaskCondition condition) {
        if(condition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            condition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            condition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        //流程类型：放款常规审批流程
        List<String> businessStatusInList = new ArrayList<>();
        businessStatusInList.add(AfsEnumUtil.key(BusinessStateInEnum.APPROVED));
        businessStatusInList.add(AfsEnumUtil.key(BusinessStateInEnum.CONDITIONAL_APPROVE));
        condition.setBusinessStatusInList(businessStatusInList);
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<LoanWaitTaskSubmitVO> loanWaitTaskSubmitVOList = loanWaitTaskService.getWaitSubmitTaskList(page, condition);
        loanWaitTaskSubmitVOList.getRecords().forEach(loanWaitTaskSubmitVO -> {
            /**标签信息表**/
            List<ApproveMakeLabel> labelList = approveMakeLabelService.list(Wrappers.<ApproveMakeLabel>query().lambda()
                    .eq(ApproveMakeLabel::getApplyNo, loanWaitTaskSubmitVO.getApplyNo()));
            loanWaitTaskSubmitVO.setLabelList(labelList);
        });
        return IResponse.success(loanWaitTaskSubmitVOList);
    }

    @PostMapping("/modifyCancle")
    @ApiOperation("批量取消申请")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyCancle(@RequestParam("data") String jsonDataArrStr) {
        try {
            String[] str = jsonDataArrStr.split(",");
            List applyNoList = new ArrayList();
            for (int i = 0; i < str.length; i++) {
                applyNoList.add(str[i]);
            }
            if(applyNoList!=null && applyNoList.size()!=0){
                applyNoList.forEach(applyNo->{
                    CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                            .eq(CaseBaseInfo::getApplyNo,applyNo));
                    caseBaseInfo.setBusinessStateIn(AfsEnumUtil.key(BusinessStateInEnum.CANCEL));
                    caseBaseInfoService.updateById(caseBaseInfo);
                    //添加案件取消记录
                    CaseApproveRecord lockOprRecord = new CaseApproveRecord();
                    lockOprRecord.setApplyNo(applyNo.toString());
                    lockOprRecord.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
                    lockOprRecord.setApproveSuggest(ApproveTypeEnum.CANAEL.getValue());
                    lockOprRecord.setApproveSuggestName("合同取消");
                    lockOprRecord.setApproveStartTime(new Date());
                    lockOprRecord.setApproveEndTime(new Date());
                    lockOprRecord.setDisposeStaff(SecurityUtils.getUser().getUserRealName());
                    lockOprRecord.setApproveType(ApproveTypeEnum.CANAEL.getValue());
                    caseApproveRecordService.save(lockOprRecord);
                    //取消信息通知进件系统
                    approveLoanInfoService.sendListToApplyNotic(jsonDataArrStr);
                });
            }
            return IResponse.success(true);
        }catch (Exception e) {
            return IResponse.fail("批量取消失败！");
        }
    }
}
